<template>
  <!-- 动态需量配置 表单 -->
  <a-modal
    v-model:open="visible"
    title="动态需量配置"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="800"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      layout="horizontal"
      :labelCol="labelCol"
      ref="formRef"
      :disabled="props.isInfo"
    >
      <a-form-item label="动态需量开关">
        <a-switch
          v-model:checked="form.isDynamic"
          :checkedValue="1"
          :unCheckedValue="0"
          @change="changeIsDynamic"
        />
      </a-form-item>
    </a-form>
    <div class="demandSug" v-if="form.isDynamic">
      <div class="sugTit">需量推荐</div>
      <a-table
        v-if="tableData?.length"
        :dataSource="tableData"
        :columns="columns"
        size="small"
        @resizeColumn="handleResizeColumn"
        :pagination="false"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'suggestValue'">
            <span
              v-if="!record.showInput"
              class="suggest"
              @click="handleSuggest(index, 'total')"
              >{{ record.suggestValue }}</span
            >
            <a-input-number
              v-else
              v-model:value="record.suggestValue"
              style="width: 120px"
              :controls="false"
              @blur="handleSuggestBlur(index, 'total')"
            />
          </template>
          <template v-if="column.key === 'handle'">
            <a-button v-hasPermission="'dynamicDemandSendMsg'" type="link" @click="handleSetCCU(record)">下发</a-button>
          </template>
        </template>
      </a-table>
      <a-table
        :dataSource="childTableData"
        :columns="childColumns"
        size="small"
        @resizeColumn="handleResizeColumn"
        :pagination="false"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'suggestValue'">
            <span
              v-if="!record.showInput"
              class="suggest"
              @click="handleSuggest(index, 'child')"
              >{{ record.suggestValue }}</span
            >
            <a-input-number
              v-else
              v-model:value="record.suggestValue"
              style="width: 120px"
              :controls="false"
              @blur="handleSuggestBlur(index, 'child')"
            />
          </template>
          <template v-if="column.key === 'handle'">
            <a-button v-hasPermission="'dynamicDemandSendMsg'" type="link" @click="handleSetCCU(record)">下发</a-button>
          </template>
        </template>
      </a-table>
      <!-- <div class="tips">
        <InfoCircleOutlined />昨日总用户功率最大值与当前需量值相差超过10%，请谨慎下发需量推荐值！！
      </div> -->
      <div class="chartContent">
        <div class="chartTit">
          历史推荐需量值
          <div class="dateFilter">
            <a-range-picker
              v-model:value="choseTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
            <a-button
              type="primary"
              class="filterBtn"
              @click="getDemandChartData"
              >查询</a-button
            >
          </div>
        </div>
        <div id="dynaminDemandConfig" class="chartContainer" />
        <!-- <a-empty style="opacity: 0.5; margin-top: 50px" v-else /> -->
      </div>
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">关闭</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>
// 
import * as echarts from "echarts"

import { chartOption, lineOption } from "./chartOption"
import { cloneDeep } from "lodash-es"

const router = useRouter()
import dayjs from "dayjs"
const $api = inject("$api")
const props = defineProps({
  demandConfigVisible: {
    type: Boolean,
    default: false,
  },
  stationId: {
    type: Number,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})
const loading = ref(false)
const visible = ref(props.demandConfigVisible)
const emits = defineEmits(["update:demandConfigVisible"])
watch(
  () => props.demandConfigVisible,
  async (val) => {
    visible.value = val
    if (val) {
      const endDate = dayjs().format("YYYY-MM-DD")
      const startDate = dayjs().subtract(6, "day").format("YYYY-MM-DD") // 前一周的日期
      choseTime.value = [startDate, endDate]
      await getIsDynamic()
      getDemandSuggest()
      getDemandChartData()
      getDemandExceed()
    }
  }
)
function handleResizeColumn(w, col) {
  col.width = w
}
const labelCol = { style: { width: "140px" } }
const formRef = ref(null)
const columns = ref([
  {
    title: "总需量",
    dataIndex: "name",
    key: "name",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "推荐需量值",
    dataIndex: "suggestValue",
    key: "suggestValue",
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 150,
    resizable: true,
    align: "center",
  },
])
const childColumns = ref([
  {
    title: "变压器需量",
    dataIndex: "name",
    key: "name",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "推荐需量值",
    dataIndex: "suggestValue",
    key: "suggestValue",
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 150,
    resizable: true,
    align: "center",
  },
])
const tableData = ref([])
const childTableData = ref([])
const form = ref({
  isDynamic: 0,
})
const cancel = () => {
  emits("update:demandConfigVisible", false)
  emits("update:isInfo", false)
  emits("update:isEdit", false)
  form.value = {
    isDynamic: 0,
  }
  formRef.value.clearValidate()
}
const changeIsDynamic = async () => {
  const params = {
    stationId: props.stationId,
    onOff: form.value.isDynamic,
  }
  const res = await $api.setDemandSwitch(params)
  getDemandChartData() // 开关变化时重新获取图表数据
}
const getIsDynamic = async () => {
  const params = {
    stationId: props.stationId,
  }
  const res = await $api.getDemandSwitch(params)
  if (res && res.code === 0) {
    form.value.isDynamic = res.data ? 1 : 0
  }
}
const getDemandSuggest = async () => {
  const params = {
    stationId: props.stationId,
  }
  const res = await $api.getDemandSuggest(params)
  if (res && res.code === 0) {
    tableData.value = res.data.totalDemands
    childTableData.value = res.data.demands
  }
}
const chartLoading = ref(false)
const chartsData = ref({})
const powerChart = ref({})
const getDemandChartData = async () => {
  chartsData.value = {}
  powerChart.value = cloneDeep(chartOption)
  chartLoading.value = true
  const params = {
    stationId: props.stationId,
    startDate: choseTime.value[0],
    endDate: choseTime.value[1],
  }
  const res = await $api.getDemandHistorySuggest(params)
  if (res && res.code === 0) {
    chartsData.value = res?.data
    const chartData = [
      ...res.data.totalDemandCurve.map((item) => {
        return {
          ...item,
          linkName: `总需量-${item.linkName}`,
        }
      }),
      ...res.data.demandCurve,
    ]
    const xAxisData = chartData[0].curve.map(
      (curveItem) => curveItem.runDay.split(" ")[0]
    )
    chartData.forEach((item) => {
      const dataValues = item.curve.map((curveItem) => curveItem.suggestValue)
      const chartOption = cloneDeep(lineOption)
      chartOption.name = item.linkName
      chartOption.data = dataValues
      powerChart.value.series.push(chartOption)
    })
    powerChart.value.xAxis.data = xAxisData
    await nextTick()
    const chartEl = document.getElementById("dynaminDemandConfig")
    if (chartEl) {
      const chartInstance = echarts.init(chartEl)
      chartInstance.resize()
      chartInstance.clear()
      chartInstance.setOption(powerChart.value)
    }
    chartLoading.value = false
  }
}
const getDemandExceed = async () => {
  const res = await $api.demandExceed({
    stationId: props.stationId,
  })
  console.log("[ res ]-302", res)
}
const choseTime = ref()
const handleSuggest = (index, type) => {
  switch (type) {
    case "total":
      tableData.value[index].showInput = true
      break
    case "child":
      childTableData.value[index].showInput = true
      break
    default:
      break
  }
}
const handleSuggestBlur = (index, type) => {
  switch (type) {
    case "total":
      tableData.value[index].showInput = false
      break
    case "child":
      childTableData.value[index].showInput = false
      break
    default:
      break
  }
}
const handleSetCCU = async (record) => {
  const requestUrl = record.publishInfo?.requestUrl
  const params = {
    linkDeviceId: record.linkId,
    items: [
      {
        requestNameAndEvent: record.publishInfo?.requestNameAndEvent,
        value: record.suggestValue,
      },
    ],
  }
  const res = await $api.setItem(params, requestUrl)
  if (res && res.code === 0) {
    message.success("保存成功")
    router.push({
      name: "Chargestrategy",
    })
  } else {
    message.error(res?.msg || "保存失败")
  }
}
onMounted(() => {})
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 300px;
}
.ant-form-item {
  margin-top: 20px;
  margin-bottom: 0;

  width: 100%;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.demandSug {
  .sugTit {
    font-size: 16px;
    margin: 20px 0 30px 0;
  }
}
.tips {
  margin-top: 10px;
  font-size: 12px;
  .anticon {
    margin-right: 5px;
    color: orange;
  }
}
.chartContainer {
  width: 100%;
  height: 400px;
}
.chartContent {
  border: 1px solid #666;
  border-radius: 4px;
  margin-top: 30px;
  .chartTit {
    font-size: 16px;
    height: 32px;
    line-height: 32px;
    margin: 12px 0 20px 10px;
  }
}
.dateFilter {
  float: right;
  margin-right: 12px;
  .filterBtn {
    margin-left: 10px;
  }
}
.suggest {
  cursor: pointer;
}
</style>
